package com.whililong.jxc.ftpservice.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpLoginException;

public class Client {

	protected Shell shell;
	private Text textHost;
	private Text textUser;
	
	private Text textPassword;
	private Text textContent;
	private Text textChgDir;
	private Label labelPrompt;
	private Label labelHost;
	private Button buttonLink;
	private Label labelUser;
	private Button buttonDisconnect;
	private Label labelPassword;
	private Label labelFileShow;
	private Label labelChgDir;
	private Button buttonCDChg;
	private Button buttonCDUP;
	private Label labelDir;
	private Text textFile;
	private Label labelFile;
	private Text textDir;
	private FtpClient myFtp = null;
	private Button buttonDownload;
	private TelnetInputStream inStream = null;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Client window = new Client();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(470, 413);
		shell.setText("FTP客户端");
		shell.setLayout(new FormLayout());
		
		Composite composite = new Composite(shell, SWT.NONE);
		FormData fd_composite = new FormData();
		fd_composite.top = new FormAttachment(0);
		fd_composite.bottom = new FormAttachment(0, 380);
		fd_composite.right = new FormAttachment(0, 450);
		fd_composite.left = new FormAttachment(0);
		composite.setLayoutData(fd_composite);
		composite.setLayout(new FormLayout());
		
		labelPrompt = new Label(composite, SWT.NONE);
		FormData fd_labelPrompt = new FormData();
		fd_labelPrompt.top = new FormAttachment(0);
		fd_labelPrompt.left = new FormAttachment(5);
		fd_labelPrompt.right = new FormAttachment(100);
		labelPrompt.setLayoutData(fd_labelPrompt);
		
		labelHost = new Label(composite, SWT.NONE);
		labelHost.setAlignment(SWT.CENTER);
		FormData fd_labelHost = new FormData();
		fd_labelHost.top = new FormAttachment(labelPrompt, 10);
		fd_labelHost.left = new FormAttachment(0, 5);
		labelHost.setLayoutData(fd_labelHost);
		labelHost.setText("主机名：");
		
		textHost = new Text(composite, SWT.BORDER);
		FormData fd_textHost = new FormData();
		fd_textHost.right = new FormAttachment(labelHost, 313, SWT.RIGHT);
		fd_textHost.left = new FormAttachment(labelHost, 5);
		fd_textHost.top = new FormAttachment(labelPrompt, 10);
		textHost.setLayoutData(fd_textHost);
		
		buttonLink = new Button(composite, SWT.NONE);
		buttonLink.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buttonLink_actionPerformed();
			}
		});
		FormData fd_buttonLink = new FormData();
		fd_buttonLink.left = new FormAttachment(100, -60);
		fd_buttonLink.top = new FormAttachment(labelPrompt, 6);
		fd_buttonLink.right = new FormAttachment(100);
		buttonLink.setLayoutData(fd_buttonLink);
		buttonLink.setText("连接");
		
		labelUser = new Label(composite, SWT.NONE);
		labelUser.setAlignment(SWT.RIGHT);
		FormData fd_labelUser = new FormData();
		fd_labelUser.top = new FormAttachment(labelHost, 15);
		fd_labelUser.left = new FormAttachment(0, 5);
		labelUser.setLayoutData(fd_labelUser);
		labelUser.setText("用户名：");
		
		buttonDisconnect = new Button(composite, SWT.NONE);
		buttonDisconnect.setEnabled(false);
		buttonDisconnect.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buttonDisconnect_actionPerformed();
			}
		});
		FormData fd_buttonDisconnect = new FormData();
		fd_buttonDisconnect.left = new FormAttachment(buttonLink, 0, SWT.LEFT);
		fd_buttonDisconnect.top = new FormAttachment(buttonLink, 6);
		fd_buttonDisconnect.right = new FormAttachment(100);
		buttonDisconnect.setLayoutData(fd_buttonDisconnect);
		buttonDisconnect.setText("断开");
		
		textUser = new Text(composite, SWT.BORDER);
		FormData fd_textUser = new FormData();
		fd_textUser.top = new FormAttachment(textHost, 6);
		fd_textUser.width = 100;
		fd_textUser.left = new FormAttachment(textHost, 0, SWT.LEFT);
		textUser.setLayoutData(fd_textUser);
		
		labelPassword = new Label(composite, SWT.NONE);
		FormData fd_labelPassword = new FormData();
		fd_labelPassword.top = new FormAttachment(textHost, 10);
		labelPassword.setLayoutData(fd_labelPassword);
		labelPassword.setText("密码：");
		
		textPassword = new Text(composite, SWT.BORDER);
		fd_labelPassword.right = new FormAttachment(textPassword, -6);
		FormData fd_textPassword = new FormData();
		fd_textPassword.top = new FormAttachment(textHost, 6);
		fd_textPassword.right = new FormAttachment(textHost, 0, SWT.RIGHT);
		fd_textPassword.left = new FormAttachment(0, 239);
		textPassword.setLayoutData(fd_textPassword);
		
		labelFileShow = new Label(composite, SWT.NONE);
		FormData fd_labelFileShow = new FormData();
		fd_labelFileShow.left = new FormAttachment(0, 5);
		fd_labelFileShow.top = new FormAttachment(textUser, 10);
		labelFileShow.setLayoutData(fd_labelFileShow);
		labelFileShow.setText("目录列表：");
		
		textContent = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL);
		FormData fd_textContent = new FormData();
		fd_textContent.bottom = new FormAttachment(labelFileShow, 150);
		fd_textContent.top = new FormAttachment(labelFileShow, 6);
		fd_textContent.right = new FormAttachment(labelPrompt, 0, SWT.RIGHT);
		fd_textContent.left = new FormAttachment(0, 5);
		textContent.setLayoutData(fd_textContent);
		
		labelChgDir = new Label(composite, SWT.NONE);
		FormData fd_labelChgDir = new FormData();
		fd_labelChgDir.top = new FormAttachment(textContent, 10);
		fd_labelChgDir.left = new FormAttachment(0, 5);
		labelChgDir.setLayoutData(fd_labelChgDir);
		labelChgDir.setText("转换目录：");
		
		textChgDir = new Text(composite, SWT.BORDER);
		FormData fd_textChgDir = new FormData();
		fd_textChgDir.top = new FormAttachment(textContent, 10);
		fd_textChgDir.left = new FormAttachment(labelChgDir, 12);
		textChgDir.setLayoutData(fd_textChgDir);
		
		buttonCDChg = new Button(composite, SWT.NONE);
		buttonCDChg.setEnabled(false);
		buttonCDChg.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buttonCDChg_actionPerformed();
			}
		});
		fd_textChgDir.right = new FormAttachment(buttonCDChg, -6);
		FormData fd_buttonCDChg = new FormData();
		fd_buttonCDChg.left = new FormAttachment(0, 256);
		fd_buttonCDChg.top = new FormAttachment(textContent, 10);
		buttonCDChg.setLayoutData(fd_buttonCDChg);
		buttonCDChg.setText("转换目录");
		
		buttonCDUP = new Button(composite, SWT.NONE);
		buttonCDUP.setEnabled(false);
		buttonCDUP.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buttonCDUP_actionPerformed();
			}
		});
		fd_buttonCDChg.right = new FormAttachment(buttonCDUP, -6);
		FormData fd_buttonCDUP = new FormData();
		fd_buttonCDUP.left = new FormAttachment(0, 341);
		fd_buttonCDUP.top = new FormAttachment(textContent, 10);
		buttonCDUP.setLayoutData(fd_buttonCDUP);
		buttonCDUP.setText("返回上级目录");
		
		labelFile = new Label(composite, SWT.NONE);
		FormData fd_labelFile = new FormData();
		fd_labelFile.left = new FormAttachment(0, 5);
		fd_labelFile.top = new FormAttachment(labelChgDir, 16);
		labelFile.setLayoutData(fd_labelFile);
		labelFile.setText("下载文件名:");
		
		textFile = new Text(composite, SWT.BORDER);
		FormData fd_textFile = new FormData();
		fd_textFile.left = new FormAttachment(textChgDir, 0, SWT.LEFT);
		fd_textFile.right = new FormAttachment(textChgDir, 0, SWT.RIGHT);
		fd_textFile.top = new FormAttachment(textChgDir, 10);
		textFile.setLayoutData(fd_textFile);
		
		labelDir = new Label(composite, SWT.NONE);
		FormData fd_labelDir = new FormData();
		fd_labelDir.left = new FormAttachment(0, 5);
		fd_labelDir.top = new FormAttachment(labelFile, 16);
		labelDir.setLayoutData(fd_labelDir);
		labelDir.setText("存放路径:");
		
		textDir = new Text(composite, SWT.BORDER);
		FormData fd_textDir = new FormData();
		fd_textDir.right = new FormAttachment(textChgDir, 0, SWT.RIGHT);
		fd_textDir.left = new FormAttachment(textChgDir, 0, SWT.LEFT);
		fd_textDir.top = new FormAttachment(textFile, 10);
		textDir.setLayoutData(fd_textDir);
		
		buttonDownload = new Button(composite, SWT.NONE);
		buttonDownload.setEnabled(false);
		buttonDownload.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buttonDownload_actionPerformed();
			}
		});
		FormData fd_buttonDownload = new FormData();
		fd_buttonDownload.left = new FormAttachment(buttonCDChg, 0, SWT.LEFT);
		fd_buttonDownload.right = new FormAttachment(buttonCDChg, 0, SWT.RIGHT);
		fd_buttonDownload.top = new FormAttachment(labelDir, 0, SWT.TOP);
		buttonDownload.setLayoutData(fd_buttonDownload);
		buttonDownload.setText("下载");
		
	}
	// 响应“连接”按钮的点击消息，连接到服务器端
	void buttonLink_actionPerformed() {
	    String hostname = textHost.getText();
	    labelPrompt.setText("正在连接，请等待.....");
	    try {
			myFtp = new FtpClient(hostname,21);      // 构造一个对象
			String user = textUser.getText();
			String psw = textPassword.getText();
			if (user.equals("")) {
				user = "anonymous";
				psw = "user@com";
				textUser.setText(user);
				textPassword.setText(psw);	
			}
			myFtp.login(user, psw);   // 以给定用户名和密码登录
			myFtp.binary();                       // 表示文件以二进制模式传输
			showFileContents();                   // 列出服务器端当前目录下的目录和文件名

	    	labelPrompt.setText("连接主机:"+textHost.getText()+"成功!");
	    	buttonDisconnect.setEnabled(true);
	    	buttonDownload.setEnabled(true);
		    buttonCDChg.setEnabled(true);
		    buttonCDUP.setEnabled(true);
	    	buttonLink.setEnabled(false);
	    }
	    catch(FtpLoginException e1) {
	      String strPrompt = "用户名密码错误";
	      labelPrompt.setText(strPrompt);
	    }
	    catch (IOException e1) {
	      String strPrompt = "连接主机:" + hostname + "失败!";
	      labelPrompt.setText(strPrompt);
	    }
	    catch(SecurityException e1) {
	      String strPrompt = "无权限与主机:" + hostname + "连接!";
	      labelPrompt.setText(strPrompt);
	    }
	}
	
	// 列出服务器端当前目录下的目录和文件名
	public void showFileContents() {
	    int ch;
	    StringBuffer buf = new StringBuffer();
	    try {
	      inStream = myFtp.list();                // 得到主机端当前目录下所有文件和目录的输入数据流
	      while ((ch=inStream.read())>=0) {      // 从输入流中读取数据
	        buf.append((char)ch);                // 保存数据到缓冲区
	      }
	      textContent.setText("");
	      textContent.append(buf.toString());    // 将目录和文件名显示在文本框中
	      inStream.close();                          // 关闭输入流
	    }
	    catch(Exception e) {
	      System.out.println("Error: " + e);
	    }
	}
	// 响应“断开”按钮的点击消息，连接到服务器端
  	void buttonDisconnect_actionPerformed() {
	    try {
	      myFtp.closeServer();                 // 关闭与服务器端的连接
	      textContent.setText("");
	      labelPrompt.setText("与主机断开连接");
	    }
	    catch(IOException e1) {
	      System.out.println("Error: " + e1);
	    }
	    buttonLink.setEnabled(true);
	    buttonDownload.setEnabled(false);
	    buttonDisconnect.setEnabled(false);
	    buttonCDChg.setEnabled(false);
	    buttonCDUP.setEnabled(false);
	}
  	
 // 转换目录
  	void buttonCDChg_actionPerformed() {
	    try {
	    	myFtp.cd(textChgDir.getText());
	    	showFileContents();                   // 列出服务器端当前目录下的目录和文件名
	    }
	    catch(IOException e1) {
	      System.out.println("Error: " + e1);
	    }
	}
  	
 // 返回上级目录
  	void buttonCDUP_actionPerformed() {
	    try {
	    	myFtp.cdUp();
	    	showFileContents();                   // 列出服务器端当前目录下的目录和文件名
	    }
	    catch(IOException e1) {
	      System.out.println("Error: " + e1);
	    }
	}
 // 响应“断开”按钮的点击消息，连接到服务器端
	void buttonDownload_actionPerformed() {
	    int ch;
	    StringBuffer buf = new StringBuffer();
	    buf.setLength(0);
	    try {
	      File dir = new File(textDir.getText());             // 构造目录
	      File f = new File(dir, textFile.getText());         // 通过文件
	      if(!f.exists())
	    	  f.createNewFile();
	      FileOutputStream out = new FileOutputStream(f);
	      //RandomAccessFile file = new RandomAccessFile(f, "rw");   // 构造一个随机访问文件
	      inStream = myFtp.get(textFile.getText()); // 得到文件的输入流
	      byte[] read = new byte[1024*1024];
	      while((ch = inStream.read(read))>=0) {                       // 读取数据流
	    	  out.write(read, 0, ch);                                  // 将读取的数据存在缓冲区中
	      }
	      out.flush();
	      out.close();                                            // 关闭文件
//	      JOptionPane msg = new JOptionPane();                     // 提示对话框
//	      JOptionPane.showMessageDialog(FtpClientFrame.this, "下载成功", "下载成功！", 1);
	      MessageDialog.openInformation(null, "下载成功", "下载成功！");
	    }
	    catch(Exception e1) {
	      System.out.println("Error: " + e1);
	    }
	}
}
